﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sispe.Entities;

namespace Sispe.Repository
{
    public class RuralRepository:MasterRepository,IRuralRepository
    {
        public List<RURAL> GetAllFromRural()
        {
            var query = from r in context.RURALs
                        select r;
            return query.ToList();
        }

        public List<RURAL> GetAllFromRuralByDescripcion(string descripcion)
        {
            var query = from r in context.RURALs
                        select r;
            if (descripcion != null && descripcion != string.Empty && descripcion != "")
            {
                query = from r in context.RURALs
                        where r.CentroPoblado.ToUpper().Contains(descripcion.ToUpper()) ||
                                   r.Caserio.ToUpper().Contains(descripcion.ToUpper())
                        select r;
            }
            return query.ToList();
        }

        public RURAL GetFromRuralById(int id)
        {
            var query = from r in context.RURALs
                        where r.IdRural.Equals(id)
                        select r;
            return query.SingleOrDefault();
        }

        public bool ExisteDuplicidad(string caserio, string centroPoblado)
        {
            var query = from r in context.RURALs
                        where r.Caserio.ToUpper().CompareTo(caserio.ToUpper()) == 0 
                        && r.CentroPoblado.ToUpper().CompareTo(centroPoblado.ToUpper()) == 0
                        select r;
            return query.Any();
        }

        public void AddRural(RURAL rural)
        {
            context.RURALs.Add(rural);
            context.SaveChanges();
        }

        public void UpdateRural(RURAL rural)
        {
            context.Entry(rural).State = System.Data.EntityState.Modified;
            context.SaveChanges();
        }

        public void RemoveRural(int id)
        {
            var existe = context.RURALs.Find(id);

            if (existe != null)
            {
                context.RURALs.Remove(existe);
                context.SaveChanges();
            }
        }
    }
}
